<template>

  <el-row :span="24">
    <el-col :span="8">
      <el-input v-model="input"
                placeholder="请输入培训班级"
                style="width:200px"
                clearable
                size="large"
      />
      <el-button type="primary" size="large" @click="searchClass">搜索</el-button>
      <el-button type="primary" size="large" @click="resClass">刷新</el-button>
    </el-col>
  </el-row>




  <!--教学班列表-->
  <el-card>
    <div class="exam-list">
      <el-table
          :data="tclassDetail.data"
          border
          style="width: 100%;"
          :empty-text="'请输入培训班级查询'"
      >
        <el-table-column
            label="序号"
            width="60"
            align="center">
          <template #default="scope">
            {{scope.$index + 1}}
          </template>
        </el-table-column>
        <el-table-column
            prop="name"
            label="教学班名称"
            width="280"
            align="center">
          <template #default="scope">
            <el-tooltip content="点击查看教学班内详情" placement="top">
                            <span class="col2-cell-style"
                                  @click="viewNClassByTClass(scope.$index)">{{scope.row.name}}</span>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column
            prop="createTime"
            label="创建时间"
            width="200"
            align="center">
        </el-table-column>
        <el-table-column
            prop="updateTime"
            label="更新时间"
            width="200"
            align="center">
        </el-table-column>
        <el-table-column
            prop="teacherName"
            label="任课老师"
            align="center">
        </el-table-column>
        <el-table-column
            prop="status"
            label="状态"
            width="100"
            align="center">
          <template #default>
            <el-tag type="success" disable-transitions>正常</el-tag>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!--分页-->
    <Pagination :currentPage="currentPage" :pageSize="pageSize" :total="total"
                :handleSizeChange="handleSizeChange" :handleCurrentChange="handleCurrentChange"></Pagination>
  </el-card>

  <!--培训班详情-->
  <el-dialog title="查看培训班学生详情" v-model="toViewStudent" fullscreen >
    <el-dialog
        v-model="innerVisible"
        width="30%"
        title="添加学生"
        append-to-body
    >
      <!-- 添加学生表 -->
      <el-form ref="loginForm1" :rules="AddstudentRule" :model="Addstudent" class="login-form">
        <el-form-item>
        </el-form-item>
        <el-form-item prop="phone">
          <el-input v-model="Addstudent.phone" placeholder="请输入学生的用户号" clearable>
          </el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="addStudentone">确认</el-button>
          <el-button @click="innerVisible = false">取消</el-button>
        </div>
      </template>
    </el-dialog>
    <!--过滤栏-->
    <div class="filter-bar">
      <el-row :sapn="24" >

        <el-col :span="2">
          <el-button type="primary" class="filter-item item-margin-left-16"
                     @click="viewNClassByTClass(currIndex), eidInput = ''">
            <i class="el-icon-refresh"></i> 刷  新
          </el-button>
        </el-col>
        <el-col :span="2">
          <el-button type="primary" class="filter-item item-margin-left-16" @click="toViewStudent = false">
            <i class="el-icon-circle-close"></i> 关闭页面
          </el-button>
        </el-col>
      </el-row>







    </div>

    <!--学生表格-->
    <el-table
        :data="studentDetail.data"
        border
        style="width: 100%"
        id="exportTable">
      <el-table-column
          label="序号"
          width="100"
          align="center">
        <template #default="scope">
          {{scope.$index + 1}}
        </template>
      </el-table-column>
      <el-table-column
          label="学号"
          prop="userId"
          width="320"
          align="center">
      </el-table-column>
      <el-table-column
          label="姓名"
          prop="realName"
          width="320"
          align="center">
      </el-table-column>
      <el-table-column
          prop="status"
          label="状态"
          align="center">
        <el-tag disable-transitions>正常</el-tag>
      </el-table-column>
    </el-table>

    <!--分页-->
    <Pagination :currentPage="stuCurPage" :pageSize="stuPageSize"
                :total="stuTotal" :handleSizeChange="handleSizeChange2"
                :handleCurrentChange="handleCurrentChange2"></Pagination>

  </el-dialog>
</template>

<script setup>
import Pagination from '@/components/PaginationNew.vue'
import{reactive, ref,onMounted} from 'vue'
import API from "@/api/trainerClass"
import { ElMessage,ElMessageBox  } from 'element-plus'
onMounted(() => {
  getTrainClass()
})
//删除弹窗
const toDeleteStudent = ref(false);
const toDeleteClass = ref(false);
// 学生界面弹窗
const currClass = ref(0)
const currIndex = ref(0)
const toViewStudent = ref(false)
let studentDetail = reactive({data:[]})
const eidInput = ref('')
const stuCurPage =  ref(1) //学生表
const stuPageSize = ref(20)
const stuTotal = ref(0)
// 添加学生弹窗
const innerVisible = ref(false)
const Addstudent = reactive({
  phone:''
})
const AddstudentRule = reactive({
  phone: [
    {required: true, message: '不可为空', trigger: 'blur'},
  ],
})
// 主界面
const input = ref('')
let tclassDetail=reactive({
      data:[]
    }
)
let toCreateTClass=ref(false)
let formLabelWidth=ref('120px')
let tclassForm=reactive({
  name:'数据结构',
  endTime: '2020-01-16 14:15:12',
  teacher: localStorage.getItem("loginusername"),
})


//清除表格
function clearForm(){
  tclassForm = reactive({
    name: '',
    nclass: [],
    endTime: '',
    teacher: localStorage.getItem("loginusername"),
  })
}
function createTClass(){
  console.log(tclassForm)
  if(tclassForm.name===''){
    ElMessage.error("班级名字不能为空")
    return;
  }
  let createTClassParams = {
    "name": tclassForm.name,
    "notes": "123",
  }
  API.createTrainClass(createTClassParams).then(res=>{
    if(res.data.success===true){
      console.log(res.data)
      ElMessage.success("创建班级成功")
      toCreateTClass.value = false
      getTrainClass()
    }else {
      console.log(res.data)
      if(areFirstNCharsEqual(res.data.message,"Expected one result (or null) to be returned by selectOne()",20)){
        ElMessage.error("创建失败，不能重复创建同名班级")
      }
      else{
        ElMessage.error("创建班级失败，请联系管理员"+`${res.data.message}`)
      }
    }
    // this.classTable=res.data
  }).catch(error=>{
    console.log(error)
  })
}
function areFirstNCharsEqual(str1, str2, n) {
  // 确保字符串长度大于等于n，以避免越界错误
  if (str1.length < n || str2.length < n) {
    return false;
  }

  // 比较前n个字符是否相等
  return str1.substring(0, n) === str2.substring(0, n);
}
function requestAllNclass(){
  return ''
}
function viewNClassByTClass(index){
  console.log(tclassDetail.data[index].id)
  currClass.value = tclassDetail.data[index].id//现在的班级号
  currIndex.value = index//现在的班级的下标用于调用自己
  // Axios({})getTrainStudent
  let getTrainStudentParams = {
    "pageNumber": stuCurPage.value,
    "pageSize": stuPageSize.value,
    "trainClassId": currClass.value,
    "companyId":localStorage.getItem('cid')
  }
  API.getTrainStudent(getTrainStudentParams).then(res=>{
    if(res.data.success===true){
      console.log(res.data)
      studentDetail.data = res.data.content.records
      stuTotal.value = res.data.content.total
      toViewStudent.value = true;
      ElMessage.success("请求班级成功")
    }else {
      console.log(res.data)
      ElMessage.error("请求班级失败，请联系管理员")
    }
    // this.classTable=res.data
  }).catch(error=>{
    console.log(error)
  })
  // 弹窗打开

  // }
}
const toChangeName = ref(false)
const currchangeClass = ref(-1)
const tclassChangeForm = reactive({name:''})
function changeTclass(id){
  toChangeName.value = true
  currchangeClass.value = id
}
function clearClassNameForm(){
  tclassChangeForm.name = ""
}
// 培训班级总页面初始
const currentPage = ref(1)
const pageSize = ref(20)
const total = ref(0)
function handleSizeChange(val) {
  pageSize.value = val;
  getTrainClass()
}
function handleCurrentChange(val) {
  currentPage.value = val;
  getTrainClass()
}
// 获取班级
function getTrainClass(){
  let getTrainClassparams = {
    "pageNumber": currentPage.value,
    "pageSize": pageSize.value,
    "companyId":localStorage.getItem('cid')
  }

  API.getTrainClass(getTrainClassparams).then(res=>{
    if(res.data.success===true){
      console.log(res.data)
      ElMessage.success("请求班级成功")
      tclassDetail.data = res.data.content.list
      for(let i = 0;i<tclassDetail.data.length;i++){

        // 创建一个新的 Date 对象，将 UTC 时间字符串作为参数传入
        let utcDate = new Date(tclassDetail.data[i].createTime);

        // 设置目标时区偏移量为 UTC-16 时区偏移量
        let offset = +16 * 60; // -16小时 * 60分钟
        let targetDate = new Date(utcDate.getTime() + (offset * 60000));

        // 获取目标时区的年、月、日、时、分
        let year = targetDate.getUTCFullYear();
        let month = (targetDate.getUTCMonth() + 1).toString().padStart(2, '0'); // 月份从 0 开始，所以要加 1
        let day = targetDate.getUTCDate().toString().padStart(2, '0');
        let hours = targetDate.getUTCHours().toString().padStart(2, '0');
        let minutes = targetDate.getUTCMinutes().toString().padStart(2, '0');

        // 构建目标时区的字符串格式（例如：2024-05-05日 14:57）
        let targetDateTimeString = `${year}-${month}-${day}日 ${hours}:${minutes}`;
        tclassDetail.data[i].createTime = targetDateTimeString
      }
      for(let i = 0;i<tclassDetail.data.length;i++){

        // 创建一个新的 Date 对象，将 UTC 时间字符串作为参数传入
        let utcDate = new Date(tclassDetail.data[i].updateTime);

        // 设置目标时区偏移量为 UTC-16 时区偏移量
        let offset = +16 * 60; // -16小时 * 60分钟
        let targetDate = new Date(utcDate.getTime() + (offset * 60000));

        // 获取目标时区的年、月、日、时、分
        let year = targetDate.getUTCFullYear();
        let month = (targetDate.getUTCMonth() + 1).toString().padStart(2, '0'); // 月份从 0 开始，所以要加 1
        let day = targetDate.getUTCDate().toString().padStart(2, '0');
        let hours = targetDate.getUTCHours().toString().padStart(2, '0');
        let minutes = targetDate.getUTCMinutes().toString().padStart(2, '0');

        // 构建目标时区的字符串格式（例如：2024-05-05日 14:57）
        let targetDateTimeString = `${year}-${month}-${day}日 ${hours}:${minutes}`;
        tclassDetail.data[i].updateTime = targetDateTimeString
      }
      total.value = res.data.content.total
      let maxp = total.value/pageSize.value
      if(total.value%pageSize.value != 0){
        maxp++
      }
      if(currentPage.value>maxp && currentPage.value > 1){
        currentPage.value = 1
        getTrainClass()
      }
    }else {
      console.log(res.data)
      ElMessage.error("请求班级失败，请联系管理员")
    }
    // this.classTable=res.data
  })
}
//搜索班级
function searchClass(){
  let getTrainClassparams = {
    "pageNumber": currentPage.value,
    "pageSize": pageSize.value,
    "name": input.value.trim() ,
    "companyId":localStorage.getItem('cid')
  }
  API.getTrainClass(getTrainClassparams).then(res=>{
    if(res.data.success===true){
      console.log(res.data)
      ElMessage.success("请求班级成功")
      tclassDetail.data = res.data.content.list
      total.value = res.data.content.total
      for(let i = 0;i<tclassDetail.data.length;i++){

        // 创建一个新的 Date 对象，将 UTC 时间字符串作为参数传入
        let utcDate = new Date(tclassDetail.data[i].createTime);

        // 设置目标时区偏移量为 UTC-16 时区偏移量
        let offset = +16 * 60; // -16小时 * 60分钟
        let targetDate = new Date(utcDate.getTime() + (offset * 60000));

        // 获取目标时区的年、月、日、时、分
        let year = targetDate.getUTCFullYear();
        let month = (targetDate.getUTCMonth() + 1).toString().padStart(2, '0'); // 月份从 0 开始，所以要加 1
        let day = targetDate.getUTCDate().toString().padStart(2, '0');
        let hours = targetDate.getUTCHours().toString().padStart(2, '0');
        let minutes = targetDate.getUTCMinutes().toString().padStart(2, '0');

        // 构建目标时区的字符串格式（例如：2024-05-05日 14:57）
        let targetDateTimeString = `${year}-${month}-${day}日 ${hours}:${minutes}`;
        tclassDetail.data[i].createTime = targetDateTimeString
      }
      for(let i = 0;i<tclassDetail.data.length;i++){

        // 创建一个新的 Date 对象，将 UTC 时间字符串作为参数传入
        let utcDate = new Date(tclassDetail.data[i].updateTime);

        // 设置目标时区偏移量为 UTC-16 时区偏移量
        let offset = +16 * 60; // -16小时 * 60分钟
        let targetDate = new Date(utcDate.getTime() + (offset * 60000));

        // 获取目标时区的年、月、日、时、分
        let year = targetDate.getUTCFullYear();
        let month = (targetDate.getUTCMonth() + 1).toString().padStart(2, '0'); // 月份从 0 开始，所以要加 1
        let day = targetDate.getUTCDate().toString().padStart(2, '0');
        let hours = targetDate.getUTCHours().toString().padStart(2, '0');
        let minutes = targetDate.getUTCMinutes().toString().padStart(2, '0');

        // 构建目标时区的字符串格式（例如：2024-05-05日 14:57）
        let targetDateTimeString = `${year}-${month}-${day}日 ${hours}:${minutes}`;
        tclassDetail.data[i].updateTime = targetDateTimeString
      }
      let maxp = total.value/pageSize.value
      if(total.value%pageSize.value != 0){
        maxp++
      }
      if(currentPage.value>maxp && currentPage.value > 1){
        currentPage.value = 1
        getTrainClass()
      }
    }else {
      console.log(res.data)
      ElMessage.error("请求班级失败，请联系管理员")
    }
    // this.classTable=res.data
  }).catch(error=>{
    console.log(error)
  })
}
//刷新主界面
function resClass(){
  getTrainClass()
  input.value = ''
}
function deleteClass(){
  let closeTrainClassparams = {"id": tclassDetail.data[currIndex.value].id}
  API.closeTrainClass(closeTrainClassparams).then(res=>{
    if(res.data.success===true){
      console.log(res.data)
      ElMessage.success("删除班级成功")
      getTrainClass()
    }else {
      console.log(res.data)
      ElMessage.error(`删除班级失败，请联系管理员,${res.data.message}`)
    }
  }).catch(error=>{
    console.log(error)
  })
  toDeleteClass.value = false;
}
function deleteTclass(index){
  toDeleteClass.value = true;
  currIndex.value = index;
}




// 班级学生页面初始


function handleSizeChange2(val) {
  stuPageSize.value = val;
  viewNClassByTClass(currIndex.value)
}
function handleCurrentChange2(val) {
  stuCurPage.value = val;
  viewNClassByTClass(currIndex.value)
}
// 选择分类
const value = ref('ALL')
const options = [
  {
    value: 'ALL',
    label: '所有培训',
  },
  {
    value: 'Myclass',
    label: '我创建的培训',
  },
]
function selectChange(){
  console.log(value.value)
}
const currUserId = ref(0)
//退出班级删除学生
function preChangeNClass(row){
  currUserId.value = row.userId
}
let homeworkDetails = reactive({data:[]})
</script>

<style scoped>
.input{
  padding-top: 5px;
  padding-right: 800px;
}
.el-button{
  padding-left: 25px;
}
.transfeLayout{
  margin-left: 120px;
  margin-bottom: 25px;

}

.transfeLayout >>> .el-transfer-panel {
  width:300px;
}
.transfeTitle{
  width: 120px;
  height: 0px;
  padding-left: 12px;
  margin-bottom: 0px;
}
.exam-list {
  width: 100%;
}
.exam-list .col2-cell-style {
  color: #409EFF;
  cursor: pointer;
}
</style>
